package com.huanzhidadi.java8inaction.chapter3;

import com.alibaba.fastjson2.JSON;
import com.huanzhidadi.java8inaction.model.Dish;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class DishTest {

    public static void main(String[] args) {
        List<Dish> menu = Arrays.asList(
                new Dish("pork", false, 800, Dish.Type.MEAT),
                new Dish("beef", false, 700, Dish.Type.MEAT),
                new Dish("season fruit", true, 120, Dish.Type.OTHER),
                new Dish("chicken", false, 400, Dish.Type.MEAT),
                new Dish("rice", true, 350, Dish.Type.OTHER),
                new Dish("pizza", true, 550, Dish.Type.OTHER),
                new Dish("prawns", false, 300, Dish.Type.FISH),
                new Dish("salmon", false, 450, Dish.Type.FISH)
        );

        // 使用流操作处理集合
        List<String> lowCalDishNames = menu.parallelStream()
                .filter(d -> d.getCalories() < 400)
                .sorted(Comparator.comparing(Dish::getCalories))
                .map(Dish::getName)
                .collect(Collectors.toList());
        log.info(JSON.toJSONString(lowCalDishNames));

        // 使用流操作对集合根据条件进行分类
        Map<Dish.Type, List<Dish>> dishesByType = menu.stream()
                .collect(Collectors.groupingBy(Dish::getType));
        log.info(JSON.toJSONString(dishesByType));

        // 中间操作在做什么
        List<String> names = menu.stream()
                .filter(d -> {
                    log.info("filtering " + d.getName());
                    return d.getCalories() > 300;
                })
                .map(d -> {
                    log.info("mapping " + d.getName());
                    return d.getName();
                })
                .limit(3)
                .collect(Collectors.toList());
        log.info(JSON.toJSONString(names));
    }
}
